﻿using BaseBll;
using BaseWebApi.App_Start;
using BaseWebApi.Common;
using BaseWebApi.Models;
using Common;
using Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;

namespace BaseWebApi.Controllers
{
    /// <summary>
    /// 物品资料
    /// </summary>
    [ControllerGroup(groupName: "Item", useage: "仓库管理（采购管理）-物品资料（分类管理）")]
    public class ItemController : BaseController
    {
        JWTPlayloadInfo playload;

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页尺寸</param>
        /// <param name="typeID">类别ID</param>
        /// <param name="itemID">物品编号</param>
        /// <param name="itemName">物品名称</param>
        /// <param name="specs">规格型号</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetPageList(int pageIndex, int pageSize, int typeID = 0, string itemID = "", string itemName = "", string specs = "")
        {
            var strWhere = "";
            if (typeID > 0)
            {
                strWhere += " and t1.TypeID = " + typeID;
            }
            if (!string.IsNullOrEmpty(itemID))
            {
                strWhere += " and t1.ItemID like '%" + itemID + "%'";
            }
            if (!string.IsNullOrEmpty(itemName))
            {
                strWhere += " and t1.ItemName like '%" + itemName + "%'";
            }
            if (!string.IsNullOrEmpty(specs))
            {
                strWhere += " and t1.Specs = " + specs;
            }

            DataTable dt = ItemBll.Instance.GetPageList(pageSize, pageIndex, strWhere, "t1.ID", out int records);
            int totalPages = PageHelper.GetPageCount(pageSize, records);
            var list = CommonOperation.ConvertDataTableToModelList<Item>(dt);

            // 获取所有物品的文件信息
            var itemIDs = list.Select(item => item.ID).ToList();
            var imgDataTable = UploadBll.Instance.GetFilesForItems(itemIDs, "Item");
            var imgData = CommonOperation.ConvertDataTableToModelList<FileData>(imgDataTable);
            // 将图片放到字典中
            var imgDict = imgData.ToDictionary(img => img.RelationId, img => img.FilePath);

            foreach (var item in list)
            {
                // Use dictionary lookup instead of querying in a loop
                if (imgDict.TryGetValue(item.ID, out string imgPath))
                {
                    item.Imgpath = imgPath;
                }
            }
            
            return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list), pageIndex, totalPages, records);
        }

        /// <summary>
        /// 查询物品列表
        /// </summary>
        /// <param name="typeID">类别id</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetList(int typeID = 0)
        {
            string strWhere = typeID > 0 ? " and t1.TypeID=" + typeID : "";

            List<Item> list = ItemBll.Instance.GetList(strWhere);

            return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
        }

        /// <summary>
        /// 根据id查询实体类
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetModelById(int ID)
        {
            if (ID > 0)
            {
                Item model = ItemBll.Instance.GetModelById(ID);
                if (model != null)
                {
                    // 查询文件
                    DataTable dt = UploadBll.Instance.GetFiles(ID, "Item");
                    model.ImgList = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                    return JsonHelper.SuccessJson(JsonHelper.ModelToJObject(model));
                }
                else
                {
                    return JsonHelper.FailJson("数据不存在");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误");
            }
        }

        /// <summary>
        /// 根据物品id查询文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetFileById(int id)
        {
            if (id <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            DataTable dt = UploadBll.Instance.GetFiles(id, "Item");
            return JsonHelper.SuccessJson(CommonOperation.DataTable2JArray(dt));
        }

        /// <summary>
        /// 新增物品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage AddItem([FromBody] Item model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                //验证各字段合法性
                string msg = "";
                bool isOk = ItemBll.Instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    bool res = ItemBll.Instance.AddItem(model);
                    if (res)
                    {
                        // 更新文件信息
                        if (model.ImgList != null && model.ImgList.Count > 0)
                        {
                            UploadBll.Instance.Update((int)model.ID, model.ImgList);
                        }
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "新增物品", Constant.ActionEnum.Add, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("新增成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "新增物品", Constant.ActionEnum.Add, Constant.StatusEnum.Fail));
                        return JsonHelper.FailJson("新增失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }

            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "新增物品:" + ex.Message, Constant.ActionEnum.Add, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 修改物品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateItem([FromBody] Item model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (model.ID <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            try
            {
                bool isExist = ItemBll.Instance.IsExist(" and ID=" + model.ID);
                if (!isExist)
                {
                    return JsonHelper.ErrorJson("不存在该数据");
                }
                //验证各字段合法性
                string msg = "";
                bool isOk = ItemBll.Instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    bool res = ItemBll.Instance.UpdateItem(model);
                    if (res)
                    {
                        // 更新文件信息
                        if (model.ImgList != null && model.ImgList.Count > 0)
                        {
                            UploadBll.Instance.Update((int)model.ID, model.ImgList);
                        }
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "修改物品", Constant.ActionEnum.Edit, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("修改成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "修改物品", Constant.ActionEnum.Edit, Constant.StatusEnum.Fail));
                        return JsonHelper.FailJson("修改失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }

            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "修改物品:" + ex.Message, Constant.ActionEnum.Edit, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 删除物品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeleteItem(int id)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (id <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            try
            {
                bool isExist = ItemBll.Instance.IsExist(" and ID=" + id);
                if (!isExist)
                {
                    return JsonHelper.ErrorJson("不存在该数据");
                }
                bool result;
                // 先删除相关图片
                DataTable dt = UploadBll.Instance.GetFiles(id, "Item");
                if (dt.Rows.Count > 0)
                {
                    List<FileData> files = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                    string fid = "";
                    for (int i = 0; i < files.Count; i++)
                    {
                        if (string.IsNullOrEmpty(fid))
                        {
                            fid = "'" + files[i].RelationId + "'";
                        }
                        else
                        {
                            fid += ",'" + files[i].RelationId + "'";
                        }
                    }
                    bool res = UploadBll.Instance.DeleteFiles(fid, "Item", files);
                    if (res)
                    {
                        result = ItemBll.Instance.DeleteItem(id.ToString());
                        if (result)
                        {
                            new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "删除物品", Constant.ActionEnum.Delete, Constant.StatusEnum.Success));
                            return JsonHelper.SuccessJson("删除成功");
                        }
                        else
                        {
                            new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "删除物品", Constant.ActionEnum.Delete, Constant.StatusEnum.Fail));
                            return JsonHelper.SuccessJson("删除失败");
                        }
                    }
                    else
                    {
                        return JsonHelper.FailJson("删除文件失败");
                    }
                }
                else
                {
                    result = ItemBll.Instance.DeleteItem(id.ToString());
                    if (result)
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "删除物品", Constant.ActionEnum.Delete, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("删除成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "删除物品", Constant.ActionEnum.Delete, Constant.StatusEnum.Fail));
                        return JsonHelper.SuccessJson("删除失败");
                    }
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "删除物品:" + ex.Message, Constant.ActionEnum.Delete, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        #region -- 物品类别相关 --
        /// <summary>
        /// 查询物品分类（树形数据）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetItemTypeToTree()
        {
            string strWhere = "";
            //if (!string.IsNullOrEmpty(search))
            //{
            //    strWhere += " and FullName like '%" + search + "%' ";
            //}

            List<ItemType> list = ItemBll.Instance.GetListTypeModels(strWhere);

            if (list.Count > 0)
            {
                return JsonHelper.SuccessJson(ItemBll.Instance.GetTreeJson(list));
            }
            else
            {
                return JsonHelper.NullJson("没有数据！");
            }
        }

        /// <summary>
        /// 获取某一分类下的所有子分类
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetTypeByName(string typeName)
        {
            List<ItemType> list = ItemBll.Instance.GetTypeByName(typeName);
            if (list == null || list.Count == 0)
            {
                return JsonHelper.ErrorJson("没有数据");
            }
            else
            {
                return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
            }
        }

        /// <summary>
        /// 新增类别
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage AddItemType([FromBody] ItemType model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                //验证各字段合法性
                string msg = "";
                bool isOk = ItemBll.Instance.VerifyModel_Type(model, ref msg);
                if (isOk)
                {
                    bool res = ItemBll.Instance.AddItemType(model);
                    if (res)
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "新增类别", Constant.ActionEnum.Add, Constant.StatusEnum.Success));
                        return JsonHelper.SuccessJson("新增成功");
                    }
                    else
                    {
                        new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "新增类别", Constant.ActionEnum.Add, Constant.StatusEnum.Fail));
                        return JsonHelper.FailJson("新增失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }

            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "新增类别:" + ex.Message, Constant.ActionEnum.Add, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        /// <summary>
        /// 删除类别
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeleteItemType(int id)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                if (id <= 0)
                {
                    return JsonHelper.FailJson("参数错误！");
                }
                else
                {
                    // 判断该类别是否被使用
                    if (ItemBll.Instance.HasUsed(id))
                    {
                        return JsonHelper.FailJson("该类别已被使用，不允许删除！");
                    }
                    else
                    {
                        if (ItemBll.Instance.DeleteItemType(id))
                        {
                            new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "删除类别", Constant.ActionEnum.Delete, Constant.StatusEnum.Success));
                            return JsonHelper.SuccessJson("删除成功！");
                        }
                        else
                        {
                            new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "删除类别", Constant.ActionEnum.Delete, Constant.StatusEnum.Fail));

                            return JsonHelper.FailJson("删除失败！");
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                new LogHelper().Error(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "删除类别:" + ex.Message, Constant.ActionEnum.Delete, Constant.StatusEnum.Exception), ex);
                throw ex;
            }
        }

        #endregion

        #region 上传文件相关

        /// <summary>
        /// 上传图片
        /// </summary>     
        /// <returns></returns>
        public HttpResponseMessage UploadPic()
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];

            List<FileData> list = new List<FileData>();
            HttpFileCollection files = HttpContext.Current.Request.Files;
            FileData model = null;
            foreach (var key in files.AllKeys)
            {
                HttpPostedFile postedFile = files[key];
                if (!string.IsNullOrEmpty(postedFile.FileName))
                {
                    // file.SaveAs(HttpContext.Current.Server.MapPath("~/imgcoll/") + file.FileName);
                    //文件扩展名，不含“.”
                    string fileExt = Utils.GetFileExt(postedFile.FileName);

                    // 图片类型
                    Regex regex = new Regex(@"gif|jpg|jpeg|png|bmp|webp");
                    bool isMatch = regex.IsMatch(fileExt);
                    if (!isMatch)
                    {
                        return JsonHelper.ErrorJson("文件类型不匹配");
                    }

                    model = UploadHelper.SaveFilePic(postedFile, UploadHelper.uploadPath + "images/pc/item/" + DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("yyyyMMddHHmmss"));

                    // 文件类型
                    model.FileType = fileExt;

                    // 关联表
                    model.RelationTable = "Item";

                    if (model != null)
                    {

                        list.Add(model);

                    }
                    else
                    {
                        continue;
                    }

                }
            }
            if (list.Count > 0)
            {
                bool result = UploadBll.Instance.AddList(list);
                if (result)
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "上传图片(relationTable:" + model.RelationTable + ")", Constant.ActionEnum.Upload, Constant.StatusEnum.Success));
                    return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
                }
                else
                {
                    return JsonHelper.ErrorJson("上传失败，稍后重试");
                }
            }
            else
            {
                return JsonHelper.ErrorJson("没有匹配的文件类型");
            }
        }

        /// <summary>
        /// 根据文件ID删除文件
        /// </summary>
        /// <param name="fileID">文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeletePic(string fileID)
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (string.IsNullOrEmpty(fileID))
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            FileData model = UploadBll.Instance.GetFileByID(fileID);
            if (model != null)
            {
                bool res = UploadBll.Instance.DeleteFilesByID(fileID, model);
                if (res)
                {
                    new LogHelper().Info(new LogContent(Utils.GetNextID(), playload.LoginIP, playload.UserName, Constant.SysModule.Item, "删除文件(ID:" + fileID + ")", Constant.ActionEnum.Delete, Constant.StatusEnum.Success));
                    return JsonHelper.SuccessJson("删除成功！");
                }
                else
                {
                    return JsonHelper.FailJson("删除失败！");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误！");
            }

        }

        #endregion

    }
}
